package com.judysen.jsqlweb.utils;

import com.judysen.jsqlweb.exceptions.ServiceException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * jsql
 */
@Component
public class JsqlContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        JsqlContext.applicationContext = applicationContext;
    }

    /**
     * 通过beanName获取bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        if (applicationContext == null) {
            throw new ServiceException(500, "应用程序没有准备好，请稍等");
        }
        return applicationContext.getBean(beanName);
    }

    /**
     *
     * @param beanName
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> cls) {
        if (applicationContext == null) {
            throw new ServiceException(500, "应用程序没有准备好，请稍等");
        }
        return applicationContext.getBean(beanName, cls);
    }

    /**
     *
     * @return
     */
    public static ApplicationContext context() {
        if (applicationContext == null) {
            throw new ServiceException(500, "应用程序没有准备好，请稍等");
        }
        return applicationContext;
    }
}
